<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
      <el-form-item label="用户名" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="外部用户id" prop="qyyxUserId">
        <el-input
          v-model="queryParams.qyyxUserId"
          placeholder="请输入外部用户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="内部用户id" prop="qyyxUserHnCode">
        <el-input
          v-model="queryParams.qyyxUserHnCode"
          placeholder="请输入内部用户id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- v-hasPermi="['qyyx:qrcode:add']" -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qyyx:qrcode:edit']"
        >修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qyyx:qrcode:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          :disabled="multiple"
          @click="submitPoster('')"
        >导出二维码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="posterPop.open=true"
        >导出海报</el-button>
      </el-col>
      <!-- v-hasPermi="['qyyx:qrcode:export']" -->
    </el-row>

    <el-table v-loading="loading" border stripe :data="qrcodeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="唯一ID" align="center" prop="id" />
      <el-table-column label="是否有效" align="center" prop="isActive" :formatter="isActiveFormat" />
      <!-- <el-table-column label="活动id" align="center" prop="qyyxAcId" /> -->
      <el-table-column label="外部用户id" align="center" prop="qyyxUserId" />
      <el-table-column label="外部用户名" align="center" prop="lzjbYl2" />
      <el-table-column label="内部用户id" align="center" prop="qyyxUserHnCode" />
      <el-table-column label="内部用户名" align="center" prop="lzjbYl1" />

      <el-table-column label="小程序二维码图片地址" align="center" prop="qyyxQrcodeImag" />
      <!-- <el-table-column label="特殊参数" align="center" prop="qyyxQrcodeScene" /> -->
      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['qyyx:qrcode:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['qyyx:qrcode:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog title="选择海报" :visible.sync="posterPop.open" width="80%" append-to-body>
      <div class="poster-list">
        <div class="poster-item" :class="{ actived:(posterPop.url==item.fileFullUrl) }" v-for="item in posterPop.list" :key="item.id" @click="onClickPoster(item)">
          <img :src="item.fileFullUrl"/>
          <el-button type="primary" @click="toPoster(item.fileFullUrl)">下载海报</el-button>
        </div>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPoster">打码导出</el-button>
        <el-button @click="posterPop.open=false">取 消</el-button>
      </div> -->
    </el-dialog>


    <el-dialog title="编辑二维码" :visible.sync="editPop.open" width="80%" append-to-body>
      <div class="edit-pop">
        <el-tabs v-model="editPop.type">
          <el-tab-pane label="内部员工" name="nb" v-if="editPop.showTab1">
            <qywx-dept-user-selector ref="nbSelector" :selectedList="editPop.nbSelected" @onSelectUser="onSelectUser" @onDelUser="onDelUser" :qyyxAcId="acId"></qywx-dept-user-selector>
          </el-tab-pane>
          <el-tab-pane label="外部人员" name="wb" v-if="editPop.showTab2">
            <el-form inline>
              <el-form-item label="人员省份" prop="qyyxUserXq1">
                <el-input
                  v-model="editPop.wbUserQueryParams.qyyxUserXq1"
                  placeholder="请输入人员省份"
                  clearable
                  size="small"
                />
              </el-form-item>
              <el-form-item label="人员城市" prop="qyyxUserXq2">
                <el-input
                  v-model="editPop.wbUserQueryParams.qyyxUserXq2"
                  placeholder="请输入人员城市"
                  clearable
                  size="small"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getWbUserList">搜索</el-button>
              </el-form-item>
            </el-form>
            <el-table border stripe :data="editPop.wbUserList" @selection-change="onSelectWbUser">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="姓名" align="center" prop="qyyxUserName" />
              <el-table-column label="电话" align="center" prop="qyyxUserPhone" />
              <el-table-column label="省份" align="center" prop="qyyxUserXq1" />
              <el-table-column label="城市" align="center" prop="qyyxUserXq2" />
              <el-table-column label="身份" align="center" prop="qyyxUserType" />
            </el-table>

            <pagination
              v-show="editPop.wbUserTotal>0"
              :total="editPop.wbUserTotal"
              :page.sync="editPop.wbUserPageNum"
              :limit.sync="editPop.wbUserPageSize"
              @pagination="getWbUserList"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditPop">确 定</el-button>
        <el-button @click="editPop.open=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改全员营销二维码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="是否有效">
          <el-select v-model="form.isActive" placeholder="请选择是否有效">
            <el-option
              v-for="dict in isActiveOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租户id" prop="lesseeId">
          <el-input v-model="form.lesseeId" placeholder="请输入租户id" />
        </el-form-item>
        <el-form-item label="活动id" prop="qyyxAcId">
          <el-input v-model="form.qyyxAcId" placeholder="请输入活动id" />
        </el-form-item>
        <el-form-item label="外部用户id" prop="qyyxUserId">
          <el-input v-model="form.qyyxUserId" placeholder="请输入外部用户id" />
        </el-form-item>
        <el-form-item label="内部用户id" prop="qyyxUserHnCode">
          <el-input v-model="form.qyyxUserHnCode" placeholder="请输入内部用户id" />
        </el-form-item>
        <el-form-item label="小程序二维码图片地址" prop="qyyxQrcodeImag">
          <el-input v-model="form.qyyxQrcodeImag" placeholder="请输入小程序二维码图片地址" />
        </el-form-item>
        <el-form-item label="特殊参数" prop="qyyxQrcodeScene">
          <el-input v-model="form.qyyxQrcodeScene" placeholder="请输入特殊参数" />
        </el-form-item>
        <el-form-item label="预留1" prop="lzjbYl1">
          <el-input v-model="form.lzjbYl1" placeholder="请输入预留1" />
        </el-form-item>
        <el-form-item label="预留2" prop="lzjbYl2">
          <el-input v-model="form.lzjbYl2" placeholder="请输入预留2" />
        </el-form-item>
        <el-form-item label="预留3" prop="lzjbYl3">
          <el-input v-model="form.lzjbYl3" placeholder="请输入预留3" />
        </el-form-item>
        <el-form-item label="预留4" prop="lzjbYl4">
          <el-input v-model="form.lzjbYl4" placeholder="请输入预留4" />
        </el-form-item>
        <el-form-item label="预留5" prop="lzjbYl5">
          <el-input v-model="form.lzjbYl5" placeholder="请输入预留5" />
        </el-form-item>
        <el-form-item label="预留6" prop="lzjbYl6">
          <el-input v-model="form.lzjbYl6" placeholder="请输入预留6" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { getToken, getLesseeId } from '@/utils/auth'
import { listUser } from "@/api/qyyx/user";
import { listQrcode, getQrcode, delQrcode, addQrcode, updateQrcode, exportQrcode, downloadQrcode } from "@/api/qyyx/qrcode";
import { getFileList } from "@/api/basic/file"
import qywxDeptUserSelector from "@/components/QywxDeptUserSelector/index"
export default {
  name: "ActivityQrcode",
  components:{qywxDeptUserSelector},
  data() {
    return {
      acId:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 全员营销二维码表格数据
      qrcodeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否有效字典
      isActiveOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isActive: 1,
        qyyxAcId: undefined,
        qyyxUserId: undefined,
        qyyxUserHnCode: undefined,
        searchValue:undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      editPop:{
        open:false,
        type:'nb',
        showTab1:false,
        showTab2:false,
        id:'',
        nbSelected:[],
        wbSelected:[],
        wbUserList:[],
        wbUserTotal:0,
        wbUserPageNum:1,
        wbUserPageSize:10,
        wbUserQueryParams:{
          qyyxUserXq1:undefined,
          qyyxUserXq2:undefined
        }
      },
      posterPop:{
        open:false,
        url:'',
        list:[]
      }
    };
  },
  created() {
    this.acId = this.$route.params.id
    this.queryParams.qyyxAcId = this.$route.params.id
    this.getList();
    this.getDicts("is_active").then(response => {
      this.isActiveOptions = response.data;
    });
    this.getFileList(this.acId, 'ACTIVITY_INFO', 'POSTER', (data)=>{
        this.posterPop.list = data
    })
  },
  methods: {
    getFileList(id,sourcessType,sourcessType2,call){
        let params = {sourcessId:id,sourcessType,sourcessType2}
        getFileList(params).then(response => {
            if (response.code === 200) {
                if(call){
                    call(response.rows)
                }
            }
        })
    },
    onClickPoster(item){
      console.log(item)
      this.posterPop.url = item.fileFullUrl
    },
    submitPoster(hbUrl){//this.posterPop.url
      if(!this.ids||!this.ids.length){
        return
      }
      axios({
          method: 'post',
          url: process.env.VUE_APP_BASE_API+'/qyyx/qrcode/qrcode/download',
          headers:{
            Authorization:'Bearer ' + getToken()
          },
          data: {quIds:this.ids, hbUrl},
          responseType: 'blob'
      }).then(res => {
            let data = res.data
            if (!data) {
                  return
            }
            let url = window.URL.createObjectURL(new Blob([data]))
            const contentDisposition = res.headers['content-disposition'] // 从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
            const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
            const result = patt.exec(contentDisposition)
            const filename = decodeURI(escape(result[1]))
            let a = document.createElement('a')
            a.style.display = 'none'
            a.href = url
            a.setAttribute('download',filename)
            document.body.appendChild(a)
            a.click() //执行下载
            window.URL.revokeObjectURL(a.href)
            document.body.removeChild(a)
      }).catch((error) => {
            console.log(error)
      })
    },
    onSelectUser(item, val){
      if(val){
        this.editPop.nbSelected.push(item)
      }else{
        this.onDelUser(item)
      }
    },
    onDelUser(item){
      let index = this.editPop.nbSelected.findIndex(obj=>{
        return obj.userId == item.userId
      })
      if(index!=-1){
        this.editPop.nbSelected.splice(index, 1)
      }
    },
    onSelectWbUser(data){
      this.editPop.wbSelected = data
    },
    submitEditPop(){
      if(this.editPop.type=='nb'){
        for(let i of this.editPop.nbSelected){
          let params = {id:this.editPop.id||'', qyyxAcId:this.acId, qyyxUserHnCode:i.userId, lzjbYl1:i.nickName}
          if(!this.editPop.id){
            addQrcode(params).then(res=>{
              this.editPop.open = false
              this.getList()
            })
          }else{
            updateQrcode(params).then(res=>{
              this.editPop.open = false
              this.getList()
            })
          }
        }
      }else if(this.editPop.type=='wb'){
        for(let i of this.editPop.wbSelected){
          let params = {id:this.editPop.id||undefined, qyyxAcId:this.acId, qyyxUserId:i.id, lzjbYl2:i.qyyxUserName}
          if(!this.editPop.id){
            addQrcode(params).then(res=>{
              this.editPop.open = false
              this.getList()
            })
          }else{
            updateQrcode(params).then(res=>{
              this.editPop.open = false
              this.getList()
            })
          }
        }
      }
    },
    getWbUserList(){
      listUser({qyyxAcId:this.acId, pageNum:this.editPop.wbUserPageNum, pageSize:this.editPop.wbUserPageSize, ...this.editPop.wbUserQueryParams}).then(response => {
        this.editPop.wbUserList = response.rows;
        this.editPop.wbUserTotal = response.total;
      });
    },
    /** 查询全员营销二维码列表 */
    getList() {
      this.loading = true;
      listQrcode(this.queryParams).then(response => {
        this.qrcodeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 是否有效字典翻译
    isActiveFormat(row, column) {
      return this.selectDictLabel(this.isActiveOptions, row.isActive);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isActive: undefined,
        lesseeId: undefined,
        qyyxAcId: undefined,
        qyyxUserId: undefined,
        qyyxUserHnCode: undefined,
        qyyxQrcodeImag: undefined,
        qyyxQrcodeScene: undefined,
        lzjbYl1: undefined,
        lzjbYl2: undefined,
        lzjbYl3: undefined,
        lzjbYl4: undefined,
        lzjbYl5: undefined,
        lzjbYl6: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.editPop.id = undefined
      this.editPop.nbSelected = []
      this.editPop.wbSelected = []
      this.editPop.type = 'nb'
      this.editPop.showTab1 = true
      this.editPop.showTab2 = true
      this.editPop.open=true
      this.getWbUserList()
      setTimeout(()=>{
        this.$refs.nbSelector.handleSearchUser()
      }, 500)

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.editPop.id = row.id
      this.editPop.nbSelected = []
      this.editPop.wbSelected = []
      if(row.qyyxUserHnCode){
        this.editPop.type = 'nb'
        this.editPop.showTab1 = true
        this.editPop.showTab2 = false
      }else if(!row.qyyxUserHnCode){
        this.editPop.type = 'wb'
        this.editPop.showTab1 = false
        this.editPop.showTab2 = true
      }
      
      this.editPop.open=true
      this.getWbUserList()
      setTimeout(()=>{
        this.$refs.nbSelector.handleSearchUser()
      }, 500)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateQrcode(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addQrcode(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除全员营销二维码编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          // return delQrcode(ids);
          return updateQrcode({id:ids, isActive:'0'})
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有全员营销二维码数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportQrcode(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    toPoster(url){
      location.href = url
    }
  }
};
</script>

<style>
  .poster-list{
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
  }
  .poster-item{
    flex: 0 0 300px;
    width: 300px;
    margin: 0 10px 20px 10px;
    padding: 10px;
    box-sizing: content-box;
    border: 2px solid transparent;
    text-align: center;
  }
  .poster-item.actived{
    border: 2px solid #1890ff;
    border-radius: 10px;
  }
  .poster-item img{
    width: 300px;
    height: 300px;
    display: block;
    margin: 0 auto;
  }
  .poster-item .el-button{
    margin-top: 10px;
  }
</style>
